package com.isyscore.os.metadata.controller;

import com.isyscore.os.metadata.dao.SysMenuMapper;
import com.isyscore.os.metadata.model.dto.BusinessSysMenuDTO;
import com.isyscore.os.metadata.model.dto.MenuDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dc
 * @Type SystemMenuController.java
 * @Desc 系统接口管理
 * @date 2022/6/16 14:51
 */
@Api(tags = "系统接口管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("${api-full-prefix:}/system")
@Slf4j
public class SystemMenuController {

    @Value("${login.name}")
    private String appName;

    @Value("${login.appCode}")
    private String appCode;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @ApiOperation(value = "菜单列表接口")
    @PostMapping("aclReturn")
    public List<MenuDTO> getMenuList() {
        List<MenuDTO> result = new ArrayList<>();
        MenuDTO menuDomain = new MenuDTO();
        List<BusinessSysMenuDTO> menuTree = sysMenuMapper.getMenuTree();
        List<BusinessSysMenuDTO> rootList = menuTree.stream().filter(e -> e.getParentCode() == null).collect(Collectors.toList());
        Map<String, List<BusinessSysMenuDTO>> parentCodeMap = menuTree.stream().filter(e -> e.getParentCode() != null).collect(Collectors.groupingBy(
                BusinessSysMenuDTO::getParentCode
        ));
        menuTree = null;
        handleToTree(rootList,parentCodeMap);
        menuDomain.setAcls(rootList);
        menuDomain.setAppName(appName);
        menuDomain.setAppCode(appCode);
        result.add(menuDomain);
        return result;
    }

    private void handleToTree(List<BusinessSysMenuDTO> rootList, Map<String, List<BusinessSysMenuDTO>> parentCodeMap) {
        if(CollectionUtils.isEmpty(rootList)){
            return;
        }
        for (BusinessSysMenuDTO businessSysMenuDTO : rootList) {
            String code = businessSysMenuDTO.getCode();
            if (parentCodeMap.containsKey(code)) {
                List<BusinessSysMenuDTO> child = parentCodeMap.get(code);
                businessSysMenuDTO.setAclList(child);
                businessSysMenuDTO.setAclModuleList(new ArrayList<>());
                handleToTree(child,parentCodeMap);
            }else{
                businessSysMenuDTO.setAclList(new ArrayList<>());
                businessSysMenuDTO.setAclModuleList(new ArrayList<>());
            }
        }
    }
}
